package com.msdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.SettingUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msdp.dto.Result;
import com.msdp.dto.ScrollResult;
import com.msdp.dto.UserDTO;
import com.msdp.entity.Blog;
import com.msdp.entity.Follow;
import com.msdp.entity.User;
import com.msdp.mapper.BlogMapper;
import com.msdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.service.IFollowService;
import com.msdp.service.IUserService;
import com.msdp.utils.SystemConstants;
import com.msdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.msdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.msdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    /**
     * 根据id查询博客详情
     * @param id
     * @return
     */
    @Override
    public Result getBlogById(Long id) {
        // 根据id获取博客详情
        Blog blog = getById(id);
        // 获取用户id
        queryBlogUser(blog);
        // 判断用户是否点赞过
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    /**
     * 分页查询博客信息
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 用户点赞博客
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result likeBlog(Long id) {

        String key = BLOG_LIKED_KEY + id;
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.ok();
        }
        Long userId = user.getId();
        // 判断是否已经点赞过
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if(score != null){
            // 如果已经点赞过
            // 更新数据库
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if(isSuccess){
                // 删除缓存
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }

            return Result.ok();
        }
        // 更新点赞数
        boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
        if(isSuccess){
            // 将点赞信息保存到Redis
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
        }
        return Result.ok();
    }

    private void isBlogLiked(Blog blog){
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result getLikesById(Long id) {
        // 查询top5的点赞用户
        String key = BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(set == null || set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 获取其中的用户id
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join( ",", ids);
        // 查询用户信息
        List<User> users = userService.query()
                                    .in("id", ids)
                                    .last("ORDER BY FIELD(id, " + idStr + ")")
                                    .list();
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 返回
        return Result.ok(userDTOS);
    }

    /**
     * 根据id查询用户发布的博客信息
     * @param userId
     * @param current
     * @return
     */
    @Override
    public Result queryUserBlog(Long userId, Integer current) {
        Page<Blog> page = query()
                .orderByDesc("liked")
                .eq("user_id", userId)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        List<Blog> records = page.getRecords();
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 新增博客
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        blog.setUserId(userId);
        // 保存探店博文
        boolean isSuccess = save(blog);
        // 博客发布成功
        if(isSuccess){
            // 将博客推送到粉丝收件箱
            // 查询所有关注作者的粉丝
            List<Follow> followUsers = followService.query().eq("follow_user_id", userId).list();
            for (Follow follow: followUsers) {
                // 将博客信息推送到粉丝收件箱
                String key = FEED_KEY + follow.getUserId();
                stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            }
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询关注用户推文
     * @param max
     * @param offset
     * @return
     */
    public Result queryFollowBlog(Long max, Integer offset) {
        // 1. 获取当前用户
        UserDTO user = UserHolder.getUser();
        // 2. 查询收件箱
        Long userId = user.getId();
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 3. 解析数据：blogId，minTime(时间戳)，offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        int os = 1;
        long minTime = 0;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        // 4. 根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id, " + idStr + ")")
                .list();

        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        // 5. 封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }
}
